import os
import typing
from datetime import date
from typing import Any, List, Tuple

from babel.support import Translations
from starlette.templating import Jinja2Templates

from fastadmin import version
from fastadmin.constants import BASE_DIR

if typing.TYPE_CHECKING:
    from fastadmin.resources import Field

templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))
templates.env.globals["VERSION"] = version.VERSION
templates.env.globals["NOW_YEAR"] = date.today().year
templates.env.add_extension("jinja2.ext.i18n")
templates.env.add_extension("jinja2.ext.autoescape")
templates.env.add_extension("jinja2.ext.with_")
templates.env.add_extension("jinja2.ext.do")

TRANSLATIONS = {
    "zh_CN": Translations.load(os.path.join(BASE_DIR, "locales"), locales=["zh_CN"]),
    "en_US": Translations.load(os.path.join(BASE_DIR, "locales"), locales=["en_US"]),
}


def set_global_env(name: str, value: Any):
    templates.env.globals[name] = value


def set_locale(locale: str):
    translations = TRANSLATIONS.get(locale) or TRANSLATIONS.get("en_US")
    templates.env.install_gettext_translations(translations)


def add_template_folder(*folders: str):
    for folder in folders:
        templates.env.loader.searchpath.append(folder)


async def render_values(
    fields: List["Field"], values: List[Tuple[Any]], display: bool = True
) -> List[List[Any]]:
    """
    render values with template render
    :param fields:
    :param values:
    :param display:
    :return:
    """
    ret = []
    for value in values:
        item = []
        for i, v in enumerate(value):
            if display:
                item.append(await fields[i].display.render(v))
            else:
                item.append(await fields[i].input.render(v))
        ret.append(item)
    return ret
